package com.bridgeintelligent.tag.webserver.logs;

import com.bridgeintelligent.tag.webserver.logs.entity.DownloadLog;
import com.bridgeintelligent.tag.webserver.logs.mapper.DownloadLogMapper;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@Component
@AllArgsConstructor
public class DownloadLogsInterceptor implements HandlerInterceptor, WebMvcConfigurer {

    private DownloadLogMapper downloadLogMapper;
    @Override
    public void addInterceptors( InterceptorRegistry registry ) {
        registry.addInterceptor( this ).addPathPatterns( "/api/customerApproval/downLoad");
    }

    @Override
    public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ) throws Exception {
        Map<String, String[]> parameterMap = request.getParameterMap();
        String[] ids = parameterMap.get("id");
        String id = null;
        if(ids!=null&&ids.length>0){
            id = ids[0];
        }
        String[] userIds = parameterMap.get("userId");
        String userId = null;
        if(userIds!=null&&userIds.length>0){
            userId = userIds[0];
        }
        // 保存logs
        if(StringUtils.isNotEmpty(id) && StringUtils.isNotEmpty(userId)){
            save(id,userId);
        }
    }
    private void save(String exportId,String userId){
        DownloadLog downloadLog = new DownloadLog().setId(IDGenerator.gen()).setParam(exportId).setUserId(userId).setCreateTime(new Date());
        downloadLogMapper.insert(downloadLog);
    }
}
